package org.linlinjava.litemall.core.util;

import org.linlinjava.litemall.db.util.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneOffset;

@Component
public class CodeUtil {

    @Autowired
    private RedisUtil redisUtil;

    /**
     * 生成团长的8位邀请码
     *
     * @return
     */
    public static String generateGroupCode() {
        String left = System.currentTimeMillis() + "";
        left = left.substring(9);
        LocalDate now = LocalDate.now();
        String monthValue = now.getMonthValue() > 9 ? now.getMonthValue() + "" : "0" + now.getMonthValue();
        String dayOfMonth = now.getDayOfMonth() > 9 ? now.getDayOfMonth() + "" : "0" + now.getDayOfMonth();
        return left + monthValue + dayOfMonth;
    }


    public String generateOrderTransNo(String code) {
        String key = "userOrderNumToday-" + code;
        Integer num = (Integer) redisUtil.get(key);
        if (num == null) {
            num = 1;
        } else {
            num++;
        }
        //计算过期时间（今日）
        long expireTime = DateTimeUtil.getStartOfDay(1).toEpochSecond(ZoneOffset.of("+8"))
                - LocalDateTime.now().toEpochSecond(ZoneOffset.of("+8"));
        redisUtil.set(key, num, expireTime);
        String left = LocalDate.now().toString().substring(2).replaceAll("-", "");
        String mid = num < 10 ? "0" + num : num + "";
        return left + mid + code;
    }

    /**
     * 拼团订单transNo生成
     *
     * @param code
     * @return
     */
    public static String generateGroupOrderTransNo(String code) {
        String left = LocalDate.now().toString().substring(2).replaceAll("-", "");
        int hour = LocalDateTime.now().getHour();
        String mid = hour < 10 ? "0" + hour : hour + "";
        return left + mid + code;
    }

    /**
     * 提现订单transNo生成
     *
     * @param code
     * @return
     */
    public static String generateCashOutTransNo(String code) {
        String left = LocalDate.now().toString().replaceAll("-", "");
        int hour = LocalDateTime.now().getHour();
        String mid = hour < 10 ? "0" + hour : hour + "";
        return left + mid + code;
    }

}
